﻿using System;
using System.Collections.ObjectModel;
using System.Linq;
using GalaSoft.MvvmLight;
using RPGOnline.Remoting.Entities;

namespace RPGOnlineWPF.ViewModel
{
	public class ChatGroupViewModel : ViewModelBase
	{
		private readonly ChatGroup m_chatGroup;
		public string Name { get { return m_chatGroup.Name; }}

		public ChatGroupViewModel()
		{
		}

		public ChatGroupViewModel(ChatGroup chatGroup)
		{
			m_chatGroup = chatGroup;
			Users = new ObservableCollection<ChatUserViewModel>();

			LoadUsers();
		}

		private void LoadUsers()
		{
			foreach (User user in m_chatGroup.Users.Values)
			{
				var chatUser = Users.FirstOrDefault(u => u.Id == user.Id);
				if (chatUser == null)
				{
					chatUser = new ChatUserViewModel(user);
					Users.Add(chatUser);
				}
				else
				{
					chatUser.Update(user);
				}
			}

			Users.Where(u => !m_chatGroup.Contains(u.Id))
				.ToList()
				.ForEach(u => Users.Remove(u));
		}

		public ObservableCollection<ChatUserViewModel> Users
		{
			get;
			private set;
		}

		public Guid Id { get { return m_chatGroup.Id; } }

		public void AddUser(User user)
		{
			var chatUser = Users.FirstOrDefault(u => u.Id == user.Id);
			if(chatUser == null)
				Users.Add(chatUser = new ChatUserViewModel(user));
			chatUser.Update(user);
		}

		public void UpdateUser(User user)
		{
			var chatUser = Users.FirstOrDefault(u => u.Id == user.Id);
			if (chatUser == null)
				Users.Add(chatUser = new ChatUserViewModel(user));
			chatUser.Update(user);
		}

		public void RemoveUser(User user)
		{
			var chatUser = Users.FirstOrDefault(u => u.Id == user.Id);
			if (chatUser != null)
				Users.Remove(chatUser);
		}
	}
}